from django.contrib.auth.backends import ModelBackend

from user.models import User


class MymodelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):

        # 判断是否是管理员登录
        if not request:
            try:
                user = User.objects.get(username=username, is_staff=True, is_superuser=True)
            except Exception as e:
                return None
            # 判断密码是否正确
            if user.check_password(password):
                return user
            else:
                return None
        else:
            # 验证用户名密码,或手机号和密码,任一个通过返回user对象
            try:
                user = User.objects.get(mobile=username)
            except Exception as e:
                try:
                    user = User.objects.get(username=username)
                except Exception as e:
                    return None
            # 使用user对象验证密码
            if user.check_password(raw_password=password):
                return user
            else:
                return None

